<template>
  <div class="api-test">
    <h2>地区数据 API 测试</h2>
    
    <div class="test-buttons">
      <button @click="testApiCall" :disabled="loading" class="test-btn">
        {{ loading ? '加载中...' : '测试 API 调用' }}
      </button>
      <button @click="clearData" class="clear-btn">
        清除数据
      </button>
    </div>
    
    <div v-if="error" class="error">
      <h3>错误信息：</h3>
      <p>{{ error }}</p>
    </div>
    
    <div v-if="apiData" class="api-result">
      <h3>API 响应数据：</h3>
      <div class="response-info">
        <p><strong>状态码：</strong>{{ apiData.code }}</p>
        <p><strong>消息：</strong>{{ apiData.message || '成功' }}</p>
        <p><strong>省份数量：</strong>{{ apiData.data?.length || 0 }}</p>
      </div>
      
      <div class="data-preview">
        <h4>数据预览（前5个省份）：</h4>
        <div class="province-list">
          <div 
            v-for="(province, index) in previewProvinces" 
            :key="province.id"
            class="province-item"
            @click="toggleProvinceDetails(province.id)"
          >
            <h5>{{ index + 1 }}. {{ province.name }} (ID: {{ province.id }})</h5>
            <p>级别：{{ province.level }}，父级ID：{{ province.pid }}</p>
            <p>子城市数量：{{ province.children?.length || 0 }}</p>
            
            <!-- 展开城市详情 -->
            <div v-if="expandedProvince === province.id && province.children" class="cities">
              <h6>城市列表：</h6>
              <div class="city-grid">
                <div 
                  v-for="city in province.children.slice(0, 6)" 
                  :key="city.id"
                  class="city-item"
                >
                  <span>{{ city.name }}</span>
                  <small>({{ city.children?.length || 0 }}个区县)</small>
                </div>
              </div>
              <p v-if="province.children.length > 6" class="more-info">
                ...还有 {{ province.children.length - 6 }} 个城市
              </p>
            </div>
          </div>
        </div>
      </div>
      
      <div class="raw-data">
        <h4>原始JSON数据（部分）：</h4>
        <pre class="json-preview">{{ jsonPreview }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getAreaCodeData, type AreaCodeResponse, type AreaItem } from '@/api/areaCode'

const apiData = ref<AreaCodeResponse | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const expandedProvince = ref<string>('')

// 计算属性
const previewProvinces = computed(() => {
  return apiData.value?.data?.slice(0, 5) || []
})

const jsonPreview = computed(() => {
  if (!apiData.value) return ''
  
  // 只显示部分数据用于预览
  const preview = {
    code: apiData.value.code,
    message: apiData.value.message,
    data: apiData.value.data?.slice(0, 2).map(province => ({
      id: province.id,
      name: province.name,
      pid: province.pid,
      level: province.level,
      children: province.children?.slice(0, 2).map(city => ({
        id: city.id,
        name: city.name,
        pid: city.pid,
        level: city.level,
        children: city.children?.slice(0, 2) || []
      })) || []
    }))
  }
  
  return JSON.stringify(preview, null, 2)
})

// 方法
async function testApiCall() {
  loading.value = true
  error.value = null
  
  try {
    const data = await getAreaCodeData()
    apiData.value = data
    console.log('地区数据加载成功:', data)
  } catch (err) {
    error.value = err instanceof Error ? err.message : '请求失败'
    console.error('API调用失败:', err)
  } finally {
    loading.value = false
  }
}

function clearData() {
  apiData.value = null
  error.value = null
  expandedProvince.value = ''
}

function toggleProvinceDetails(provinceId: string) {
  expandedProvince.value = expandedProvince.value === provinceId ? '' : provinceId
}
</script>

<style scoped>
.api-test {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 30px;
}

.test-buttons {
  text-align: center;
  margin-bottom: 30px;
}

.test-btn, .clear-btn {
  padding: 12px 24px;
  margin: 0 10px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.test-btn {
  background-color: #3498db;
  color: white;
}

.test-btn:hover:not(:disabled) {
  background-color: #2980b9;
}

.test-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.clear-btn {
  background-color: #95a5a6;
  color: white;
}

.clear-btn:hover {
  background-color: #7f8c8d;
}

.error {
  background-color: #fee;
  border: 1px solid #fcc;
  border-radius: 6px;
  padding: 20px;
  margin: 20px 0;
  color: #c33;
}

.api-result {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
}

.response-info {
  background-color: white;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
  border-left: 4px solid #27ae60;
}

.response-info p {
  margin: 5px 0;
  color: #2c3e50;
}

.data-preview {
  margin: 20px 0;
}

.province-list {
  margin-top: 15px;
}

.province-item {
  background-color: white;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.province-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-color: #3498db;
}

.province-item h5 {
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.province-item p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.cities {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e9ecef;
}

.cities h6 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.city-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  margin-bottom: 10px;
}

.city-item {
  background-color: #f1f2f6;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.city-item span {
  font-weight: 500;
  color: #2c3e50;
}

.city-item small {
  color: #666;
  display: block;
  margin-top: 2px;
}

.more-info {
  color: #666;
  font-style: italic;
  font-size: 14px;
}

.raw-data {
  margin-top: 30px;
}

.json-preview {
  background-color: #2c3e50;
  color: #ecf0f1;
  padding: 20px;
  border-radius: 6px;
  font-size: 12px;
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

h3, h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .api-test {
    padding: 10px;
  }
  
  .test-buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .test-btn, .clear-btn {
    margin: 5px 0;
    width: 200px;
  }
  
  .city-grid {
    grid-template-columns: 1fr;
  }
}
</style>